package fun.diaoer.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

/**
 * 时间工具类
 * @author benniao
 *
 */
public class DateUtil {
	
	public static String DATE_FORMAT_DATEONLY = "yyyy-MM-dd"; // 年/月/日
	public static String YYYYMMDD = "yyyyMMdd"; // 年/月/日
	public static String YYYY="yyyy";
	public static String HHmmss="HHmmss";
	public static String DATE_FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss"; // 年/月/日
	public static String DATE_FORMAT_DATETIMEMin = "yyyy-MM-dd HH:mm"; // 年/月/日
	

	/**
	 * 获取今天日期
	 * @return
	 */
	public static Date getToday() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY,0);
		todayStart.set(Calendar.MINUTE,0);
		todayStart.set(Calendar.SECOND,0);
		todayStart.set(Calendar.MILLISECOND,0);
		return todayStart.getTime();
	}
	
	/**
	 * 转化为date
	 * @param str
	 * @param parsePatterns
	 * @return
	 */
	public static Date parseDate(String str, String parsePatterns){
		if(StringUtils.isBlank(str)||("-".equalsIgnoreCase(str)&&str.startsWith("-"))){
			return null;
		}
		Date result=null;
		try {
			 DateUtils.parseDate(str, new String[] { parsePatterns });
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public static String parseDateToStr(Date date,String pattern){
		SimpleDateFormat sdf=new SimpleDateFormat(pattern);
		return sdf.format(date);
	}
	
	/**
     * date2比date1多的天数
     * @param date1    
     * @param date2
     * @return    
     */
    public static int differentDays(Date date1,Date date2){
    	if(date1==null){
    		return 0;
    	}
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年            
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }else{
            return day2-day1;
        }
    }
}
